<template>
    <!-- 富文本渲染组件 -->
    <div :class="['render-text', { 'editMode': previewOption.mode === 'edit' && element.options.edit }]" :style="{
        'margin-top': `${element.options.margin.top}px`,
        'margin-left': `${element.options.margin.left}px`,
        'margin-right': `${element.options.margin.right}px`,
        'margin-bottom': `${element.options.margin.bottom}px`,
        'padding-top': `${element.options.padding.top}px`,
        'padding-left': `${element.options.padding.left}px`,
        'padding-right': `${element.options.padding.right}px`,
        'padding-bottom': `${element.options.padding.bottom}px`
    }">
        <div :style="{
            'font-size': element.style.fontSize,
            'line-height': `${element.style.lineHeight}pt`,
            'letter-spacing': `${element.options.letterSpacing}px`,
            'transform': `scale(${element.options.scale.x}, ${element.options.scale.y})`,
            'text-align': `${element.options.textAlign ? 'justify' : 'initial'}`,
            'text-align-last': `${element.options.textAlignLast ? 'justify' : 'initial'}`
        }"
        :class="[{ 'overflow': element.options.overflow }, `overflow-line${element.options.lineClamp}`]">
            <el-select class="render-test-edit-select"
                v-if="element.options.edit && previewOption.mode == 'edit' && element.options.editSelect == 'select'"
                v-model="element.options.contentHTML"
                filterable
                placeholder="">
                <el-option v-for="(item, index) in selectOption"
                    :key="index"
                    :label="item[element.options.editSelectLabel] || item['label']"
                    :value="item[element.options.editSelectValue] || item['value']">
                </el-option>
            </el-select>
            <div ref="content"
                v-else
                class="render-text-content"
                :contenteditable="element.options.edit && previewOption.mode == 'edit'"
                spellcheck="false"
                v-html="element.options.contentHTML"
                @input="inputChange"
                @blur="inputBlur">
            </div>
        </div>
    </div>
</template>

<script>
import Observer from "@/utils/eventBus.js";
export default {
    name: "RenderText",
    props: {
        element: {
            type: Object
        },
        Api: {
            type: Object
        },
        apiIndex: {
            type: Number,
            default: 0
        },
        previewOption: {
            type: Object
        },
        index: {
            type: Number
        }
    },
    data() {
        return {
            selectOption: []
        }
    },
    methods: {
        bindAnchor() { // 绑定锚点
            let anchorId = '';
            let field = (this.element.options.anchorField && this.element.options.anchorField.split(':')) || null;
            if (field && field.length > 0) {
                let data = this.Api.options[Number(field[0])]?.data || null;
                if (Array.isArray(data)) {
                    anchorId = data[this.apiIndex][field[1]];
                } else if (data) {
                    anchorId = data?.[field[1]];
                }
                this.$refs.content.classList.add('anchor');
                this.$refs.content.anchorId = anchorId;
            }
        },
        inputChange(e) {
            // innerHTML 数据值（包含dom元素标签）
            // 1.改填写数据需要进行提取逻辑
            if (this.element.options.dataReturnField && this.element.options.dataReturnField.length > 0) {
                Observer.$emit('dataReturnField', {
                    index: this.index,
                    field: this.element.options.dataReturnField,
                    value: e.target.innerText || "" // 仅提取数据值（不含dom元素标签）
                });
            }
        },
        inputBlur(e) {
            // 1.存储数据
            if (this.element.options.edit && this.previewOption.mode == 'edit') {
                this.element.options.contentHTML = e.target.innerHTML || "";
                this.element.options.content = e.target.innerText || "";
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            let content = this.$refs.content || null;
            if (content) {
                let fieldDom = content.querySelectorAll('.field-dom');
                fieldDom.forEach(item => {
                    let field = item.innerText && item.innerText.split(':');
                    if (field && field.length > 0) {
                        let innerText = "";
                        let data = this.Api.options[Number(field[0])]?.data || null;
                        if (Array.isArray(data)) { // 数组,择为多页面渲染数据
                            innerText = data[this.apiIndex][field[1]];
                        } else if (data) { // 对象
                            innerText = data?.[field[1]];
                        }
                        // innerText = this.Api.options[Number(field[0])]?.data?.[field[1]];
                        if (Number.isFinite(innerText)) item.innerHTML = innerText;
                        else if (innerText && innerText.length > 0) item.innerHTML = innerText;
                        else item.innerHTML = null;
                        // else item.innerHTML = item.innerText;
                    }
                })
                // 绑定锚点
                if (this.element.options.anchor) this.bindAnchor();
            } else { // 弃用
                // 已经配置接口数据渲染
                if (this.element.options.editSelectApi) {
                    let apiData = this.Api.options.find(item => item.api === this.element.options.editSelectApi) || null;
                    this.selectOption = apiData.data || [];
                }
            }
            // 编辑加载时回显提取数据
            if (this.element.options.dataReturnField && this.element.options.content) Observer.$emit('dataReturnField', {
                index: this.index,
                field: this.element.options.dataReturnField,
                value: this.element.options.content // 仅提取数据值（不含dom元素标签）
            });
        })
    }
}
</script>
